package priv.hh.controller;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import priv.hh.constant.Constant;
import priv.hh.entity.Post;

import java.io.IOException;

public class IndexController {

    @FXML
    private TextField url;
    @FXML
    private TextField labelUrl;
    @FXML
    private TextField labelMethod;
    @FXML
    private TextField labelStatus;
    @FXML
    private TextField labelTime;
    @FXML
    private TextField labelSize;
    @FXML
    private TextArea response;
    @FXML
    private TableView<Post> table;
    @FXML
    private TableColumn<Post, String> methodColumn;
    @FXML
    private TableColumn<Post, String> addressColumn;
    @FXML
    private TableColumn<Post, String> statusColumn;
    private ObservableList<Post> personData = FXCollections.observableArrayList();
    private CloseableHttpClient httpClient = HttpClients.custom().build();

    /**
     * delete点击事件
     * @param actionEvent
     */
    public void delete(ActionEvent actionEvent)  {
        HttpDelete httpDelete = new HttpDelete(url.getText());
        handerRequest(httpDelete, Constant.SysConstant.DELETE.getValue());
    }

    /**
     * post点击事件
     * @param actionEvent
     */
    public void post(ActionEvent actionEvent) {
        HttpPost httpPost = new HttpPost(url.getText());
        handerRequest(httpPost, Constant.SysConstant.POST.getValue());
    }

    /**
     * get点击事件
     * @param actionEvent
     */
    public void get(ActionEvent actionEvent) {
        HttpGet Httpget = new HttpGet(url.getText());
        handerRequest(Httpget, Constant.SysConstant.GET.getValue());
    }

    /**
     * put点击事件
     * @param actionEvent
     */
    public void put(ActionEvent actionEvent) {
        HttpPut httpPut = new HttpPut(url.getText());
        handerRequest(httpPut, Constant.SysConstant.PUT.getValue());
    }

    @FXML
    private void initialize(){
        methodColumn.setCellValueFactory(cellData -> cellData.getValue().methodProperty());
        addressColumn.setCellValueFactory(cellData -> cellData.getValue().urlProperty());
        statusColumn.setCellValueFactory(cellData -> cellData.getValue().statusProperty());

        table.setItems(personData);
        table.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Post>() {
            @Override
            public void changed(ObservableValue<? extends Post> observable, Post oldValue, Post newValue) {
                if (newValue!=null) {
                    labelUrl.setText(newValue.getUrl());
                    labelMethod.setText(newValue.getMethod());
                    labelStatus.setText(newValue.getStatus());
                    labelTime.setText(newValue.getResponseTime());
                    labelSize.setText(newValue.getBodySize());
                    response.setText(newValue.getBody());
                }
            }
        });
    }

    /**
     * 处理请求
     * @param httpRequest
     * @param Method
     */
    private void handerRequest(HttpRequestBase httpRequest, String Method){
        try {
            long startTime = System.currentTimeMillis();
            if (url.getText()==null || url.getLength()<=0) {
                throw new IOException("地址不能为空");
            }
            CloseableHttpResponse httpResponse = httpClient.execute(httpRequest);
            long endTime = System.currentTimeMillis();
            String body = EntityUtils.toString(httpResponse.getEntity());

            Post post = new Post(Method, url.getText(), String.valueOf(httpResponse.getStatusLine().getStatusCode()),
                    endTime - startTime + "ms", body.length() / 1000 + "KB", body);
            personData.add(post);
            table.getSelectionModel().selectLast();
        } catch (IOException e) {
            response.setText(e.getMessage());
        }
    }

    /**
     * 清除数据
     * @param actionEvent
     */
    public void removeListData(ActionEvent actionEvent) {
        personData.clear();

        labelUrl.setText("");
        labelMethod.setText("");
        labelStatus.setText("");
        labelTime.setText("");
        labelSize.setText("");
        response.setText("");
    }
}
